package top.tenebrous.yzl.im.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import top.tenebrous.yzl.im.context.ImContext;

import java.util.*;

/**
 * @author yazhang6
 */
@Component
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    @Autowired
    private ImContext imContext;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
            String type = servletServerHttpRequest.getServletRequest().getParameter("type");
            String clientName = servletServerHttpRequest.getServletRequest().getParameter("clientName");
            if ("INSTANCE".equals(type)) {
                attributes.put("clientId", clientName + "-" + UUID.randomUUID().toString().replace("-", ""));
            } else {
                attributes.put("userId", servletServerHttpRequest.getServletRequest().getParameter("userId"));
                // TODO 根据用户id获取用户信息
                attributes.put("sessionNo", "NO." + servletServerHttpRequest.getServletRequest().getParameter("userId") + "." + UUID.randomUUID().toString().replace("-", ""));

                List<Map.Entry<ImWebsocketInterceptor, Integer>> sortList = imContext.handlerInterceptorSorted();
                // 执行扩展拦截
                for (Map.Entry<ImWebsocketInterceptor, Integer> entry : sortList) {
                    Map<String, Object> attributesMap = entry.getKey().afterImWebSocketInterceptorProcessor(servletServerHttpRequest.getServletRequest().getParameter("userId"));
                    attributes.putAll(attributesMap);
                }
            }
        }
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }


}